<template>
  <div>
    <qf-image-cropper
      :width="500"
      :height="500"
      :radius="30"
      @crop="handleCrop"
    ></qf-image-cropper>
  </div>
</template>

<script setup>
  import { ref } from 'vue'
  import { useUsercodeStore } from '@/store/usercode.js'
  import { http } from '@/utils/http.js'

  const avatarToken = ref('')
  const avatarUrl = ref('')
  const url = ref('')

  async function handleCrop(e) {
    const userCodeStore = useUsercodeStore()
    console.log(e.tempFilePath)
    // 七牛云
    const res = await http.request({
      url: '/api/config/qiUpload',
      method: 'POST',
      data: {},
    })
    avatarToken.value = res.data.uptoken
    url.value = res.data.domain
    //将头像保存到后端
    uni.uploadFile({
      url: 'https://upload-z0.qiniup.com/',
      filePath: e.tempFilePath, //头像文件
      header: {},
      formData: {
        token: avatarToken.value,
      },
      name: 'file',
      success: async (uploadFileRes) => {
        console.log(uploadFileRes.data)
        avatarUrl.value = url.value + JSON.parse(uploadFileRes.data).key
        const res = await http.request({
          url: '/api/user/upUser',
          method: 'POST',
          data: {
            field: 'himg',
            val: avatarUrl.value,
          },
        })
        if (res.st == 1) {
          uni.utils.toast('设置头像成功,即将返回')
          userCodeStore.setHimg(avatarUrl.value)
          setTimeout(() => {
            uni.navigateBack({ delta: 1 })
          }, 2000)
        } else {
          uni.utils.toast(res.msg)
        }
      },
    })
  }
</script>
